package com.demo.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.dto.Result;
import com.demo.entity.ShopType;
import com.demo.mapper.TbShopTypeMapper;
import com.demo.service.IShopTypeService;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.demo.utils.RedisConstants.CACHE_SHOP_TYPE_LIST_KEY;
import static com.demo.utils.RedisConstants.CACHE_SHOP_TYPE_LIST_TTL;


/**
* @author 小雷
* @description 针对表【tb_shop_type】的数据库操作Service实现
* @createDate 2025-10-04 14:34:58
*/
@Service
public class ShopTypeServiceImpl extends ServiceImpl<TbShopTypeMapper, ShopType>
    implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {

        String key = CACHE_SHOP_TYPE_LIST_KEY;

        // 查询缓存
        String cacheTypeListJson = stringRedisTemplate.opsForValue().get(key);

        // 缓存命中, 且是 JSONArray 类型(避免脏数据), 直接返回
        if(StrUtil.isNotBlank(cacheTypeListJson) && JSONUtil.isTypeJSONArray(cacheTypeListJson)){
            return Result.ok(JSONUtil.toList(cacheTypeListJson, ShopType.class));
        }
        // 缓存未命中, 查询数据库
        List<ShopType> shopTypeList = query().orderByDesc("sort").list();
        // 数据库未命中, 返回错误信息
        if(CollUtil.isEmpty(shopTypeList)){
            return Result.fail("商铺类型不存在!");
        }
        // 数据库命中, 写入缓存
        stringRedisTemplate.opsForValue().set(key,
                JSONUtil.toJsonStr(shopTypeList),CACHE_SHOP_TYPE_LIST_TTL, TimeUnit.MINUTES);
        // 返回类型
        return Result.ok(shopTypeList);
    }
}




